package YAPserver;

import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedInputStream;
import java.io.File;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.URL;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;

import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;

import YAPenvironment.YAPconstant;
import YAPserver.FormServer.ExitListener;

/**
 * A testing class to test different parts of the server
 */
@SuppressWarnings("unused")
public class testingClasses extends JFrame implements KeyListener, ActionListener{
	
	
	private static JTextField portTF;
	private static JButton create;
	private static JButton send;
	private static JTextField input;
	private static JTextArea output;
	private static JScrollPane jScrollPane;
	private static JLabel jLabel1;
	private static JLabel jLabel3;
	private static JScrollPane jScrollPane1;
	private static JSplitPane jSplitPane;
	private static JLabel labelClients;
	private static JList jList1;
	private static JScrollPane jScrollPane2;
	private static Thread t;
	
	
	static JTextField editLobbyName;
	static JTextField editPlayerCount;
	
	public static void main(String[] args){
		//testHighScore();
		
		//jOptionPaneDemo();
		
		//openCreateDialog();
		
		//inputDialog();
		
		//testPlayedGames();
		
		//new testingClasses();	
		
		//testMSSocket();
		
//		playSound();
		
//		try {
//			playSound2();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		
		//playSound3();
		
		//openPDF();
		
		new testingClasses();
		
		
	}
	
	public testingClasses(){
		
		setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		
			try {
		        // Set System L&F
		      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

			 } catch(Exception e){
		    	System.out.println("Couldn't set Look-and-Feel");
			 }
			
			setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
	        getContentPane().setLayout(new java.awt.GridBagLayout());

	        
	        jLabel1 = new javax.swing.JLabel();
	        portTF = new javax.swing.JTextField();
	        create = new javax.swing.JButton();
	        input = new javax.swing.JTextField();
	        send = new javax.swing.JButton();
	        labelClients = new javax.swing.JLabel();
	        jLabel3 = new javax.swing.JLabel();
	        jSplitPane = new javax.swing.JSplitPane();
	        jScrollPane1 = new javax.swing.JScrollPane();
	        output = new javax.swing.JTextArea();
	        jScrollPane2 = new javax.swing.JScrollPane();
	        jList1 = new javax.swing.JList();
	        
	        
	        jLabel1.setText("PORT:");
	        c = new java.awt.GridBagConstraints();
	        c.gridx = 0;
	        c.gridy = 0;
	        c.anchor = java.awt.GridBagConstraints.NORTHWEST;
	        c.insets = new java.awt.Insets(35, 10, 0, 0);
	        getContentPane().add(jLabel1, c);

	        portTF.setText("jTextField1");
//	        portTF.addActionListener(this);
	        c = new java.awt.GridBagConstraints();
	        c.gridx = 2;
	        c.gridy = 0;
	        c.gridwidth = 2;
	        c.gridheight = 2;
	        c.ipadx = 53;
	        c.anchor = java.awt.GridBagConstraints.NORTHWEST;
	        c.insets = new java.awt.Insets(32, 3, 0, 0);
	        getContentPane().add(portTF, c);

	        create.setText("start Server");
	        c = new java.awt.GridBagConstraints();
	        c.gridx = 4;
	        c.gridy = 0;
	        c.gridheight = 3;
	        c.ipadx = 301;
	        c.anchor = java.awt.GridBagConstraints.NORTHWEST;
	        c.insets = new java.awt.Insets(31, 6, 0, 0);
	        getContentPane().add(create, c);

	        input.setText("jTextField1");
	        c = new java.awt.GridBagConstraints();
	        c.gridx = 0;
	        c.gridy = 5;
	        c.gridwidth = 6;
	        c.ipadx = 808;
	        c.anchor = java.awt.GridBagConstraints.NORTHWEST;
	        c.insets = new java.awt.Insets(7, 10, 0, 0);
	        getContentPane().add(input, c);

	        send.setText("send");
	        send.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
	        c = new java.awt.GridBagConstraints();
	        c.gridx = 6;
	        c.gridy = 5;
	        c.gridheight = 2;
	        c.anchor = java.awt.GridBagConstraints.NORTHWEST;
	        c.insets = new java.awt.Insets(6, 6, 11, 10);
	        getContentPane().add(send, c);

	        labelClients.setText("Clients");
	        c = new java.awt.GridBagConstraints();
	        c.gridx = 0;
	        c.gridy = 3;
	        c.gridwidth = 2;
	        c.anchor = java.awt.GridBagConstraints.NORTHWEST;
	        c.insets = new java.awt.Insets(11, 10, 0, 0);
	        getContentPane().add(labelClients, c);

	        jLabel3.setText("Console");
	        c = new java.awt.GridBagConstraints();
	        c.gridx = 2;
	        c.gridy = 3;
	        c.anchor = java.awt.GridBagConstraints.NORTHWEST;
	        c.insets = new java.awt.Insets(11, 10, 0, 0);
	        getContentPane().add(jLabel3, c);

	        output.setColumns(20);
	        output.setRows(5);
	        jScrollPane1.setViewportView(output);

	        jSplitPane.setRightComponent(jScrollPane1);

	        jList1.setModel(new javax.swing.AbstractListModel() {
	            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
	            public int getSize() { return strings.length; }
	            public Object getElementAt(int i) { return strings[i]; }
	        });
	        jScrollPane2.setViewportView(jList1);

	        jSplitPane.setLeftComponent(jScrollPane2);

	        c = new java.awt.GridBagConstraints();
	        c.gridx = 0;
	        c.gridy = 4;
	        c.gridwidth = 7;
	        c.ipadx = 822;
	        c.ipady = 427;
	        c.anchor = java.awt.GridBagConstraints.NORTHWEST;
	        c.insets = new java.awt.Insets(6, 10, 0, 10);
	        getContentPane().add(jSplitPane, c);
	        
	        

	        pack();
			
	        setTitle("Server");
			setIconImage(YAPconstant.ICONIMAGE);
			setLocationRelativeTo(null);
//			addWindowListener(new ExitListener());
			
			setResizable(true);
			
//			if( !YAPconstant.C_DEBUG )
//				redirectSystemStreams();
			setDefaultCloseOperation(EXIT_ON_CLOSE);
			setVisible(true);
		}
		
		
		
	private void addComponents (JFrame frame, GridBagConstraints c){
		
		c.gridx = 0;
        c.gridy = 0;
        c.anchor = java.awt.GridBagConstraints.NORTHWEST;
        c.insets = new Insets(35, 57, 0, 0);
        add(new JLabel("PORT:"), c);

        portTF.setText(""+YAPserver.C_PORT);
        c = new java.awt.GridBagConstraints();
        c.gridx = 1;
        c.gridy = 0;
        c.gridheight = 2;
        c.ipadx = 53;
        c.anchor = java.awt.GridBagConstraints.NORTHWEST;
        c.insets = new Insets(32, 10, 0, 0);
        add(portTF, c);

        output.setColumns(20);
        output.setRows(5);
        jScrollPane.setViewportView(output);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 3;
        c.gridwidth = 10;
        c.fill = GridBagConstraints.BOTH;
        c.ipadx = 555;
        c.ipady = 345;
        c.anchor = GridBagConstraints.NORTHWEST;
        c.weightx = 1.0;
        c.weighty = 1.0;
        c.insets = new Insets(11, 10, 0, 10);
        add(jScrollPane, c);

        create.setText("start Server");
        c = new GridBagConstraints();
        c.gridx = 2;
        c.gridy = 0;
        c.gridwidth = 4;
        c.gridheight = 3;
        c.ipadx = 301;
        c.anchor = GridBagConstraints.NORTHWEST;
        c.insets = new Insets(31, 6, 0, 0);
        add(create, c);

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 4;
        c.gridwidth = 3;
        c.ipadx = 507;
        c.anchor = GridBagConstraints.SOUTHEAST;
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(7, 10, 0, 0);
        add(input, c);

        send.setText("send");
        c = new GridBagConstraints();
        c.gridx = 5;
        c.gridy = 4;
        c.gridwidth = 5;
        c.gridheight = 2;
        c.anchor = GridBagConstraints.EAST;
        c.insets = new Insets(6, 10, 11, 10);
		
		
	}
	
	

	private static void openPDF(){
		try{
			Desktop
            .getDesktop()
            .open(
                    new File(
                            "C:/Users/DMiagi/workspace/Repo/Protokoll/Handbuch.pdf"));
		}catch (Exception e){
			
		}
	}
	
//	private static void playSound2() throws Exception{
//
//		//My pfusch:
//		URL soundURL= YAPconstant.getSound(YAPconstant.Sound.bounce);
//		
//		AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundURL);
//		AudioFormat format = audioInputStream.getFormat();
//		
//		TargetDataLine line;
//		DataLine.Info info = new DataLine.Info(TargetDataLine.class, 
//		    format); // format is an AudioFormat object
//		if (!AudioSystem.isLineSupported(info)) {
//		    	System.out.println("line is not supported");
//		    	return;
//		}
//
//		try {
//		    line = (TargetDataLine) AudioSystem.getLine(info);
//		    line.open(format);
//		} catch (LineUnavailableException ex) {
//			System.out.println("line couldn't be obtained");
//		}
//		
//		Clip clip = (Clip) AudioSystem.getLine(info);
//		clip.open(audioInputStream);
//		clip.start();
//		clip.close();
//	}
		

//	private static void playSound() {
//    	try{
//	        URL url = YAPconstant.getSound(YAPconstant.Sound.bounce);
//	        Clip clip = AudioSystem.getClip();
//	        // getAudioInputStream() also accepts a File or InputStream
//	        AudioInputStream ais = AudioSystem.
//	            getAudioInputStream( url );
//	        clip.open(ais);
//	        // loop continuously
//	        clip.loop(-1);
//	        SwingUtilities.invokeLater(new Runnable() {
//	            public void run() {
//	                // A GUI element to prevent the Clip's daemon Thread
//	                // from terminating at the end of the main()
//	                JOptionPane.showMessageDialog(null, "Close to exit!");
//	            }
//	        });
//    	}catch (Exception e){
//    		e.printStackTrace();
//	    	}
//	}
//	
//	
//	//kath's pfusch (mit workaround ums Clip clip = AudioSystem.getClip(), weil das bei mir immer
//	//IllegalArgumentexception wirft)
//	private static void playSound3() {
//    	try{
//    		AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(YAPconstant.getSound(YAPconstant.Sound.bounce));
////			BufferedInputStream bufferedInputStream = new BufferedInputStream(audioInputStream);
//			AudioFormat af = audioInputStream.getFormat();
//			int size = (int) (af.getFrameSize() * audioInputStream.getFrameLength());
////			byte[] audio = new byte[size];
//			
//			DataLine.Info info = new DataLine.Info(Clip.class, af, size);
//			Clip clip = (Clip) AudioSystem.getLine(info);
//		
////          bufferedInputStream.read(audio, 0, size);
//			clip.open(audioInputStream);
//	        // loop continuously
//	        clip.loop(-1);
//	        SwingUtilities.invokeLater(new Runnable() {
//	            public void run() {
//	                // A GUI element to prevent the Clip's daemon Thread
//	                // from terminating at the end of the main()
//	                JOptionPane.showMessageDialog(null, "Close to exit!");
//	            }
//	        });
//    	}catch (Exception e){
//    		e.printStackTrace();
//	    	}
//	}
		
		
	
	static void testMSSocket(){
		
		int port= 4446;
		String MC_group="225.0.0.1";
		
		try{
			MulticastSocket socket = new MulticastSocket(port);
			InetAddress group = InetAddress.getByName(MC_group);
			socket.joinGroup(group);
			
			byte[] b= ("hallo").getBytes(); 
			DatagramPacket bla = new DatagramPacket(b,b.length, InetAddress.getByName(MC_group), port);
			socket.send(bla);

			DatagramPacket packet;
			for (int i = 0; i < 5; i++) {
			    byte[] buf = new byte[256];
			    packet = new DatagramPacket(buf, buf.length);
			    socket.receive(packet);

			    String received = new String(packet.getData());
			    System.out.println("Quote of the Moment: " + received);
			}

			socket.leaveGroup(group);
			socket.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	public static void receiving(MulticastSocket socket) throws Exception{
		while(true){
			byte[] in = new byte[100];
			DatagramPacket pack = new DatagramPacket(in, in.length, InetAddress.getByName("225.0.0.1"),1337);
			
			System.out.println("receiving...");
			socket.receive(pack);
			System.out.println("\""+new String(pack.getData())+"\" received");
		}
	}

//	testingClasses(){
//		JFrame frame = new JFrame("test");
//		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//		frame.setSize(new Dimension(300,300));
//		frame.addKeyListener(this);
//		frame.setVisible(true);
//	}
	
	private static void testPlayedGames() {
		PlayedGames.addGame("lobby1", new String[]{"name1","name2","schwuppsi"});
		PlayedGames.addGame("lobb2", new String[]{"name1","name2","yuppi","huppiduppi"});
		PlayedGames.addGame("lo1", new String[]{"name1","name2","NAAAME"});
		PlayedGames.addGame("lobby1", new String[]{"name1","name2"});
		PlayedGames.addGame("lobby1", new String[]{"name1","name2"});
		
		
		System.out.println(PlayedGames.getPlayedGames());
	}

	private static void inputDialog() {
		JPanel panel = new JPanel();
		// Populate your panel components here.
		int ret = JOptionPane.showConfirmDialog(null, panel, "Title", JOptionPane.YES_NO_OPTION);
		if ( ret == JOptionPane.YES_OPTION )
		{
		  // Read component values.
		}
		
		
		
	}

	/*
	 * if (e.getSource().equals(btnCreateLobby)){
			openCreateDialog();
			if(!editPlayerCount.getText().equals("")&&!editLobbyName.getText().equals("")){
				DataModul.parseThread.writeMessage(Command.createLobby.toString()+sep 
						+ editLobbyName.getText().replace(YAPconstant.cmdSeparator, "").replace(YAPconstant.separator, "").replace(" ", "")
						+ sep+editPlayerCount.getText());
			}
		}
	 */
	public static void openCreateDialog(){
		JPanel pnlCreateLobby = new JPanel();
		pnlCreateLobby.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		c.gridx = 0; c.gridy=0;
		c.insets = new Insets(10,10,10,10);
		c.anchor = GridBagConstraints.WEST;
		pnlCreateLobby.add(new JLabel("Name: "),c);
		c.gridx = 1;
		editLobbyName = new JTextField("Enter Name");
		pnlCreateLobby.add(editLobbyName,c);
		c.gridx = 0; c.gridy = 1;
		pnlCreateLobby.add(new JLabel("Number of Players: "),c);
		c.gridx = 1;
		editPlayerCount = new JTextField("Enter Number");
		pnlCreateLobby.add(editPlayerCount,c);
		c.gridx = 2;c.gridy=2;
		JDialog dlgCreateLobby = new JOptionPane(pnlCreateLobby).createDialog( "Create Game");
		dlgCreateLobby.setVisible(true);
	}
	
	private static void jOptionPaneDemo() {
		String firstNumber, //first string entered by user 
        secondNumber; // second string entered by user 

		int number1,     // first number to add 
		number2,    //second number to add 
		sum;                //sum of number1 and number2 

		//read in the first number from user as a string 
		firstNumber = 
       JOptionPane.showInputDialog ( "Enter first integer" ); 

		//read in the second number from user as a string 
		secondNumber = 
       JOptionPane.showInputDialog ( "Enter second interger" ,"jane"); 

		//convert numbers from type String to type int 
		number1 = Integer.parseInt ( firstNumber); 
		number2 = Integer.parseInt ( secondNumber); 

		//add the numbers 
		sum = number1 + number2; 

		//display the results 
		JOptionPane.showMessageDialog ( 
				null, "The sum is " + sum, "Results", 
				JOptionPane.PLAIN_MESSAGE); 
		System.exit ( 0 );
		
	}

	private static void testHighScore() {
		HighScore.createHighScore("Dario");
		HighScore.increaseHighScore("Dario");
		HighScore.increaseHighScore("Dario");
		HighScore.increaseHighScore("MAX");
		HighScore.increaseHighScore("MAX");
		HighScore.createHighScore("MAX");
		HighScore.increaseHighScore("A");
		HighScore.createHighScore("Dario");
		HighScore.increaseHighScore("MAX");
		HighScore.increaseHighScore("MAX");
		HighScore.increaseHighScore("MAX");
		HighScore.increaseHighScore("A");
		HighScore.increaseHighScore("B");
		System.out.println(HighScore.getHighScore());
	}

	@Override
	public void keyTyped(KeyEvent e) {
		System.out.println("typed");
	}

	@Override
	public void keyPressed(KeyEvent e) {
		System.out.println("pressed");
	}

	@Override
	public void keyReleased(KeyEvent e) {
		System.out.println("released");
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		
	}
}